package com.htfyun.factorytest.factorytestui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.widget.TextView;

import androidx.annotation.Nullable;

import java.util.List;

import com.htfyun.factorytest.R;
import com.htfyun.factorytest.device.DeviceAttr;
import com.htfyun.factorytest.utils.DebugLog;
import com.htfyun.factorytest.utils.ReflectUtils;

public class FactorySdCardActivity extends FactoryBaseActivity {
    private TextView mTxtInfo;
    private StorageManager sm;
    private static final int MSG_SDCARD_PASS = 0x100;
    private static final int MSG_OK_DELAY = 2000;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        updateUIWhileSDCardMounted();
    }

    @Override
    int getLayoutId() {
        return R.layout.activity_factory_tf_card;
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {
        mTxtInfo = findViewById(R.id.txtInfo);
    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {
        switch (msg.what) {
            case MSG_SDCARD_PASS:
                finishWithOK();
                break;

            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerSdcardReceiver();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterSdcardReceiver();
    }

    private void registerSdcardReceiver() {
        if (!DeviceAttr.getRunningDeviceAttr().hasSDCard()) {
            return;
        }

        mContext.registerReceiver(sdcardReceiver, getIntentFilterOfSDCard());

    }

    private void unregisterSdcardReceiver() {
        if (!DeviceAttr.getRunningDeviceAttr().hasSDCard()) {
            return;
        }

        mContext.unregisterReceiver(sdcardReceiver);

    }


    private final BroadcastReceiver sdcardReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }
            DebugLog.e("sdcard action = " + action + ", intent.getData() = " + intent.getData());

            updateUIWhileSDCardMounted();

        }
    };

    private void updateUIWhileSDCardMounted() {
        mTxtInfo.setText(R.string.sdcard_test_ejected);
        if (!isSDCardInserted()) {
            return;
        }

        String path = getSDCardPath();
        if (TextUtils.isEmpty(path)) {
            return;
        }
        FactoryTestItemsEnum.sdcard.setResult(mContext, getString(R.string.test_result_pass));

        try {
            StatFs stat = new StatFs(path);
            String result = FactoryTestItemsEnum.sdcard.getResult(mContext);

            String infoString = mContext.getString(R.string.sdcard_test_inserted_info,
                    Formatter.formatFileSize(mContext, stat.getTotalBytes()),
                    Formatter.formatFileSize(mContext, stat.getFreeBytes()),
                    result);

            mTxtInfo.setText(infoString);

            getHandler().sendEmptyMessageDelayed(MSG_SDCARD_PASS, MSG_OK_DELAY);

        } catch (IllegalArgumentException ignore) {

        }

    }

    private boolean isSDCardInserted() {

        if (sm == null) {
            return false;
        }

        List<StorageVolume> volList = sm.getStorageVolumes();
        if (volList.isEmpty()) {
            return false;
        }

        for (StorageVolume vol : volList) {
            DebugLog.i("vol state = " + vol.getState() + ", desc = " + vol.getDescription(mContext));

        }

        for (StorageVolume vol : volList) {
            if (vol.getState().equals(Environment.MEDIA_MOUNTED) && vol.isRemovable()) {
                return true;

            }
        }

        return false;

    }

    private String getSDCardPath() {
        if (!isSDCardInserted()) {
            return "";
        }

        StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
        if (sm == null) {
            return "";
        }

        List<StorageVolume> volList = sm.getStorageVolumes();
        if (volList.isEmpty()) {
            return "";
        }

        for (StorageVolume vol : volList) {
            if (vol.getState().equals(Environment.MEDIA_MOUNTED) && vol.isRemovable()) {
                String getPath = (String) ReflectUtils.invokeMethodWithNoException(vol, "getPath");
                DebugLog.i("desc = " + vol.getDescription(mContext) + ", StoragePath---> " + getPath);
                return getPath;
            }
        }
        return "";

    }

    private IntentFilter getIntentFilterOfSDCard() {
        IntentFilter intentFilter = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        intentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
        intentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);

        intentFilter.addDataScheme("file");

        return intentFilter;
    }
}
